package com.freedom.monitor.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.freedom.monitor.myeye.config.service.ServiceTemplateConfigService;
import com.freedom.monitor.myeye.config.service.ServiceTemplateResult;
import com.freedom.monitor.utils.ExclusionStrategyUtils;
import com.freedom.monitor.utils.StringUtils;
import com.freedom.rpc.thrift.common.utils.Logger;
import com.freedom.rpc.thrift.common.utils.SocketUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@Controller
@RequestMapping(value = "/serviceTemplate")
public class ServiceTemplateController {
	//
	private static final Logger logger = Logger.getLogger(ServiceTemplateController.class);

	// 首页进来
	@RequestMapping(value = "/index", method = { RequestMethod.GET })
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.debug("ServiceTemplateController.index for query...");
		return new ModelAndView("serviceTemplate/index", model);// 返回user/user.jsp
	}

	// 查询所有用户
	@RequestMapping(value = "/query", method = { RequestMethod.GET }, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String query(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.info("ServiceTemplateController.query invoked...");
		try {
			// 1)先获取type参数
			String page = request.getParameter("page");
			String rows = request.getParameter("rows");
			if (false == StringUtils.valid(page, rows)) {
				page = "1";
				rows = "10";
			}
			int intPage = Integer.parseInt(page.trim());
			int intRows = Integer.parseInt(rows.trim());
			logger.debug("received --->" + "page->" + page + " rows:" + rows);
			// 2)尝试获取远程服务结果
			ServiceTemplateResult result = new ServiceTemplateResult();
			logger.debug("try to get ConfigService.Client configServiceClient");
			ServiceTemplateConfigService.Client configServiceClient = (ServiceTemplateConfigService.Client) SocketUtils
					.getSyncAopObject(ServiceTemplateConfigService.Client.class);
			logger.debug("succeed to get ConfigService.Client configServiceClient");
			result = configServiceClient.queryServiceTemplate(intPage, intRows);
			// 3)分析结果
			if (null != result && true == result.isSucceed() && null != result.getServiceTemplateList()
					&& result.getServiceTemplateListSize() >= 0) {
				// 正确且有数据
				Gson gson = new GsonBuilder().setExclusionStrategies(ExclusionStrategyUtils.getInstance()).create();
				String str = "" + "{\"total\":" + result.getTotal() + ","//
						+ "\"rows\":" + gson.toJson(result.getServiceTemplateList())//
						+ "}";
				logger.debug("" + str);
				return str;
			}
			throw new Exception("query product result is not valid");
		} catch (Exception e) {
			return "{\"total\":0,\"rows\":[]}";
		}
	}

	// 新增
	@RequestMapping(value = "/addOrUpdate", method = {
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String addOrUpdate(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.debug("ServiceTemplateController.addOrUpdate() invoked...");
		try {
			// 1)获取参数
			String serviceId = request.getParameter("serviceId");
			String serviceName = request.getParameter("serviceName");
			String serviceCode = request.getParameter("serviceCode");
			String totalCount = request.getParameter("totalCount");
			String thresholdCount = request.getParameter("thresholdCount");
			String alarmPeriod = request.getParameter("alarmPeriod");
			String succeedRatioThreshold = request.getParameter("succeedRatioThreshold");
			String averageTimeCostThreshold = request.getParameter("averageTimeCostThreshold");
			String maxTimeCostThreshold = request.getParameter("maxTimeCostThreshold");
			String minTimeCostThreshold = request.getParameter("minTimeCostThreshold");
			String maxInvokedCount=request.getParameter("maxInvokedCount");
			String minInvokedCount=request.getParameter("minInvokedCount");
			String desc = request.getParameter("desc");
			if (false == StringUtils.valid(serviceName, serviceCode, //
					totalCount, thresholdCount, alarmPeriod, //
					succeedRatioThreshold, averageTimeCostThreshold, maxTimeCostThreshold, minTimeCostThreshold, //
					maxInvokedCount,minInvokedCount)) {
				throw new Exception("invalid parameter...");
			}
			// 继续执行
			// 2)调用远程的程序
			logger.debug("try to get UserService.Client userServiceClient");
			ServiceTemplateConfigService.Client configServiceClient = (ServiceTemplateConfigService.Client) SocketUtils
					.getSyncAopObject(ServiceTemplateConfigService.Client.class);
			logger.debug("succeed to get UserService.Client userServiceClient");
			boolean result = false;
			if (null != serviceId && serviceId.trim().length() > 0) {
				logger.debug("action->edit");
				result = configServiceClient.editServiceTemplate(serviceName, serviceCode, Integer.parseInt(totalCount),
						Integer.parseInt(thresholdCount), Integer.parseInt(alarmPeriod),
						Integer.parseInt(succeedRatioThreshold), Integer.parseInt(averageTimeCostThreshold),
						Integer.parseInt(maxTimeCostThreshold), Integer.parseInt(minTimeCostThreshold), desc,
						serviceId,Integer.parseInt(maxInvokedCount),Integer.parseInt(minInvokedCount));
			} else {
				logger.debug("action->add");
				result = configServiceClient.addServiceTemplate(serviceName, serviceCode, Integer.parseInt(totalCount),
						Integer.parseInt(thresholdCount), Integer.parseInt(alarmPeriod),
						Integer.parseInt(succeedRatioThreshold), Integer.parseInt(averageTimeCostThreshold),
						Integer.parseInt(maxTimeCostThreshold), Integer.parseInt(minTimeCostThreshold), desc,
						Integer.parseInt(maxInvokedCount),Integer.parseInt(minInvokedCount));
			}
			// 拿到了结果
			if (true == result) {
				// 正确且有数据
				return "{\"success\":true}";
			} else {
				return "{\"success\":false}";
			}
		} catch (Exception e) {
			return "{\"success\":false,\"errorMsg\":\"" + e.toString() + "\"}";
		}
	}

	// 删除
	@RequestMapping(value = "/del", method = { RequestMethod.POST }, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String delete(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.info("ServiceTemplateController.delete invoked...");
		boolean result = false;
		try {
			// 1)先获取id
			String serviceId = request.getParameter("serviceId");
			if (false == StringUtils.valid(serviceId)) {
				throw new Exception("invalid serviceId--->" + serviceId);
			}
			logger.debug("received to be delete serviceId --->" + serviceId);
			// 2)尝试获取远程服务结果
			logger.debug("try to get ConfigService.Client configServiceClient");
			ServiceTemplateConfigService.Client configServiceClient = (ServiceTemplateConfigService.Client) SocketUtils
					.getSyncAopObject(ServiceTemplateConfigService.Client.class);
			logger.debug("succeed to get ConfigService.Client configServiceClient");
			result = configServiceClient.deleteServiceTemplate(serviceId);
			// 拿到了结果
			if (true == result) {
				// 正确且有数据
				return "{\"success\":true}";

			} else {
				return "{\"success\":false}";
			}
		} catch (Exception e) {
			return "{\"success\":false,\"errorMsg\":\"" + e.toString() + "\"}";
		}
	}
}
